import java.util.Arrays;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2024-11-30
 * Time: 11:10
 */
public class HashBucket2<K,V> {
    static class Node<K,V> {
        public K key;
        public V value;
        public Node<K,V> next;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashBucket2<?, ?> that = (HashBucket2<?, ?>) o;
        return usedSize == that.usedSize && Arrays.equals(tables, that.tables);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(usedSize);
        result = 31 * result + Arrays.hashCode(tables);
        return result;
    }

    public Node<K,V>[] tables = (Node<K,V>[]) new Node[10];
    public int usedSize = 0;
    public static final double DEFAULT_LOAD_FACTOR = 0.75F;
    public void push(K key,V value) {
        int hashcode = key.hashCode();
        int index = hashcode % tables.length;
        Node<K,V> cur = tables[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> node = new Node<>(key, value);
        node.next = tables[index];
        tables[index] = node;
        usedSize++;
        while(doLoadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node<K,V>[] newTables = (Node<K,V>[]) new Node[2*tables.length];
        for (int i = 0; i < tables.length; i++) {
            Node<K,V> cur = tables[i];
            while(cur != null) {
                int hash = cur.key.hashCode();
                int index = hash % newTables.length;
                Node<K,V> curN = cur.next;
                cur.next = newTables[index];
                newTables[index] = cur;
                cur = curN;
            }
        }
        tables = newTables;
    }

    private double doLoadFactor() {
        return usedSize*1.0 / tables.length;
    }
    public V getVal(K key) {
        for (int i = 0; i < tables.length; i++) {
            int hashcode = key.hashCode();
            int index = hashcode % tables.length;
            Node<K,V> cur = tables[index];
            while(cur != null) {
                if(cur.key.equals(key)) {
                    return cur.value;
                }
                cur = cur.next;
            }
        }
        return null;
    }
}
